<template>
  <div style="margin: 50px">
    <el-form
      ref="editGoods"
      :model="goods"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      hide-required-asterisk
    >
      <!-- 第一行 -->
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="goods.name" size="small" style="width: 200px" />
      </el-form-item>
      <!-- 第二行 -->
      <div style="display: flex">
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="goods.price" size="small" style="width: 100px" />
        </el-form-item>
        <el-form-item label="商品类型" prop="type">
          <el-select
            v-model="goods.type"
            placeholder="请选择"
            size="small"
            style="width: 100px"
          >
            <el-option
              v-for="item in goodsType"
              :key="item._id"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <!-- 第三行 -->
      <div style="display: flex">
        <el-form-item label="商品状态">
          <el-tooltip :content="goods.status ? '出售' : '停售'" placement="top">
            <el-switch
              v-model="goods.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-value
            />
          </el-tooltip>
        </el-form-item>
        <el-form-item label="审核状态" style="margin-left: 60px">
          <el-select
            v-model="goods.check"
            placeholder="请选择"
            size="small"
            style="width: 100px"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <!-- 第四行 上传图片 -->
      <div style="display: flex">
        <el-form-item label="商品略缩图" label-width="100px">
          <el-upload
            :class="{ hide: hideUploadT }"
            action="/resource/goods/updateimg"
            list-type="picture-card"
            ref="uploadT"
            :auto-upload="false"
            :limit="1"
            :on-success="successT"
            :on-change="changeT"
            :on-remove="removeT"
            :file-list="fileListT"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品详情图" label-width="100px">
          <el-upload
            :class="{ hide: hideUploadD }"
            action="/resource/goods/updateimages"
            list-type="picture-card"
            ref="uploadD"
            :auto-upload="false"
            :limit="5"
            :on-success="successD"
            :on-change="changeD"
            :on-remove="removeD"
            multiple
            :on-exceed="exceedD"
            :file-list="fileListD"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </div>
      <!-- 第五行 描述 -->
      <el-form-item label="商品描述">
        <el-input
          type="textarea"
          v-model="goods.desc"
          style="width: 300px"
          rows="3"
        ></el-input>
      </el-form-item>
      <!-- 第六行 -->
      <el-form-item>
        <el-button type="primary" @click="submitForm('editGoods')" size="small"
          >修改</el-button
        >
        <el-button @click="$router.push('/goods')" size="small">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getProduct } from "../../api/product";
import goodsApi from "../../api/goods";
import config from "../../utils/config";
export default {
  data() {
    return {
      count: 0,
      hideUploadT: false,
      hideUploadD: false,
      fileListT: [],
      fileListD: [],
      delImg: [],
      goods: {
        userId: "",
        name: "",
        price: "",
        type: "",
        status: "",
        check: "",
        desc: "",
        img: [],
        images: [],
        // 做效验和数据无关
      },
      rules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
      },
      goodsType: [],
      options: [
        {
          value: -1,
          label: "未通过",
        },
        {
          value: 0,
          label: "待审核",
        },
        {
          value: 1,
          label: "已通过",
        },
      ],
    };
  },
  async beforeCreate() {
    const type = await getProduct();
    this.goodsType = type.map((item) => {
      return { value: item.typeOne, label: item.typeOne };
    });
    const data = await goodsApi.getOne(this.$route.params._id);
    // 处理图片数据
    this.fileListT = data.img.map((item) => {
      return { url: config["resource_server"] + item };
    });
    this.fileListD = data.images.map((item) => {
      return { url: config["resource_server"] + item };
    });
    // 判断
    this.hideUploadT = this.fileListT.length >= 1;
    this.hideUploadD = this.fileListD.length >= 5;
    Object.assign(this.goods, data);
    console.log(this.goods);
  },
  methods: {
    async submitForm(formName) {
      // this.goods.images.map(async (item) => {
      //   await goodsApi.delImg(item);
      // });
      // this.$refs.uploadD.submit();
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (
            this.$refs.uploadT.uploadFiles.length > 0 &&
            this.$refs.uploadD.uploadFiles.length > 0
          ) {
            await this.submit();
            setTimeout(() => {
              this.del();
            }, 1000);
          } else {
            this.$message.error("请添加图片");
          }
        } else {
          console.log("error");
        }
      });
    },
    async del() {
      // 删除img图片
      this.goods.img.map((item, index) => {
        this.delImg.map((items) => {
          if (item == items) {
            this.goods.img.splice(index, 1);
          }
        });
      });
      // 删除images图片
      const n = this.goods.images.length;
      for (let i = n - 1; i >= 0; i--) {
        this.delImg.map((items) => {
          if (this.goods.images[i] == items) {
            this.goods.images.splice(i, 1);
          }
        });
      }
      // 删除数据图片
      this.delImg.map(async (item) => {
        if (/common/.test(item)) {
          await goodsApi.delImg(item);
        }
      });
      const data = await goodsApi.update(this.goods);
      if (data) {
        this.$message({ type: "success", message: "修改成功" });
        this.$router.replace("/goods");
      }
    },
    async submit() {
      await this.$refs.uploadT.submit();
      await this.$refs.uploadD.submit();
    },
    async successT(res) {
      this.goods.img.push(res.url);
    },
    async successD(res) {
      this.goods.images.push(res.url);
    },
    exceedD() {
      this.$message({ type: "warning", message: "详情图最多添加5张" });
    },
    changeT(file, fileList) {
      this.hideUploadT = fileList.length >= 1;
    },
    changeD(file, fileList) {
      this.hideUploadD = fileList.length >= 5;
    },
    removeT(file, fileList) {
      this.delImg.push(file.url.split(config["resource_server"])[1]);
      this.hideUploadT = fileList.length >= 1;
    },
    removeD(file, fileList) {
      this.delImg.push(file.url.split(config["resource_server"])[1]);
      this.hideUploadD = fileList.length >= 5;
    },
  },
};
</script>

<style lang="scss">
.hide .el-upload--picture-card {
  display: none;
}
</style>
